﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLib.BasicServices.Plugin;
using Tracy.DataModel;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using SharedLib.Helpers;

namespace Tracy.Plugins.SourceParsers
{
    public class XSLTSourceParser : ISourceParser
    {
        static Dictionary<string, System.Xml.Xsl.XslCompiledTransform> cachedXslTransforms = new Dictionary<string, System.Xml.Xsl.XslCompiledTransform>();
        //public XmlDocument GetRawResources(FeedSource source, Entry entry)
        //{
        //    string url = source.GenerateUrl(entry);
        //    XmlDocument doc = new XmlDocument();
        //    doc.Load(url);
        //    return GetRawResources(source, doc);
        //}

        public XmlDocument GetRawResources(FeedSource source, XmlDocument doc)
        {
            string xsltMapping = source.Properties["mapping"];
            if (String.IsNullOrEmpty(xsltMapping)) throw new Exception("Mapping not found in feedsource");//TODO: Config Exception here

            XslCompiledTransform xslt;
            if (!cachedXslTransforms.ContainsKey(xsltMapping))
            {
                xslt = new XslCompiledTransform();
                xslt.Load(xsltMapping);
                cachedXslTransforms.Add(xsltMapping, xslt);
            }
            else
            {
                xslt = cachedXslTransforms[xsltMapping];
            }

            return XmlHelper.PerformXslTrasform(doc, xslt);
        }
    }
}
